<template>
  <div>
    标题:<a-input style="width: 300px" v-model:value="question['text']"></a-input>
    排他:
    <div>
      <h3>排他规则：</h3>
      <div v-for="option in question.options" :key="option.value" style="margin-bottom: 10px;">
        <strong>选项: {{ option.text }}</strong>

        <!-- 获取当前选项的排他逻辑 -->
        <a-checkbox-group
            v-model:value="exclusiveInput[option.value]"
            :options="checkboxOptions"
            style="margin-left: 10px"
        >
        </a-checkbox-group>

        <!-- 更新排他逻辑 -->
        <a-button type="primary" @click="updateExclusiveRule(option.value)" style="margin-left: 10px">更新排他项</a-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, defineProps, reactive, ref} from 'vue';
import {useQuestions} from "@/utils/paper.js";
const { getQuestionById } = useQuestions()
const props = defineProps({
  questionId:{
    type: String
  }
});
const questionId=props.questionId;// 该题的id
const question=getQuestionById(questionId) ;// 根据Id查询题目——为啥这玩意是双向绑定的？
// 用于存储排他项的输入框内容，初始化时填充当前排他项
const exclusiveInput = reactive({});

// 获取与选项 value 匹配的排他规则
const getExclusiveRule = (value) => {
  return question.ruleLogic.exclusive.find(rule => rule.value === value);
};

// 初始化多选框的选中状态（当页面加载时，填充已有的排他规则）
question.options.forEach(option => {
  const rule = getExclusiveRule(option.value);
  exclusiveInput[option.value] = rule ? [...rule.exclusive] : []; // 若存在排他规则，初始化选中的值
});

// 多选框的可选项，显示所有其他选项
const checkboxOptions = computed(() => {
  return question.options.map(option => ({
    label: option.text,
    value: option.value
  }));
});

// 更新排他项
const updateExclusiveRule = (value) => {
  const selectedExclusive = exclusiveInput[value];

  // 找到并更新排他规则
  const rule = getExclusiveRule(value);
  if (rule) {
    rule.exclusive = selectedExclusive; // 更新排他项
  } else {
    // 如果没有找到现有规则，则添加一个新规则
    question.ruleLogic.exclusive.push({
      value: value,
      exclusive: selectedExclusive
    });
  }
};
</script>
